package com.kyang.musiconline.controller;

import com.kyang.musiconline.model.ResponseData;
import com.kyang.musiconline.model.Vinyl;
import com.kyang.musiconline.service.VinylService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author kyang
 */
@RestController
@CrossOrigin
public class IndexController {
    @Autowired
    private VinylService vinylService;

    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public ResponseData search(String keywords) {
        List<Vinyl> result = new ArrayList<>();
        if (keywords != null) {
            String[] keywordsSplit=keywords.split(" ");
            for (String keyword : keywordsSplit) {
                result.addAll(vinylService.getAllVinylByKeyword(keyword));
            }
        }
        ResponseData responseData;
        if (!result.isEmpty()) {
            responseData = new ResponseData(200, true, "success", result.stream().distinct().toList());
        } else {
            responseData = new ResponseData(201, false, "No result for searching", null);
        }
        return responseData;
    }

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public ResponseData getInfo() {
        List<Vinyl> result = vinylService.getIndex();
        return new ResponseData(200, true, "success", result);
    }
}
